#!/bin/bash
# connect remote bluetooth serial port device.

bt_dev_name=yxt-e71

btinit=/etc/init.d/bluetooth
btkeyword=bluetooth

btcomportid=0
btcomport=rfcomm$btcomportid
btcomdev=/dev/$btcomport

if [ "`which pskill`" = "" ]; then
    haspskill=0
    btprocess=`ps aux|grep $btkeyword |grep -v 'grep' |awk '{print $NF}'`
else
    haspskill=1
    btprocess=`pskill -l $btkeyword |awk '{print $NF}'`
fi
echo
if [ "$btprocess" = "" ]; then
    echo "starting $btkeyword..." 
    sudo $btinit start 
    #sudo hciconfig hci0 up
else
    echo "${btprocess##*/} already running!"
fi 

echo -e "\nScanning hci dev [$bt_dev_name]..."
echo "------------------------------"
bt_dev_mac=`hcitool scan |grep ${bt_dev_name} |awk '{print $1}'`
channel=`sdptool search SP |grep Channel |awk '{print $2}'`

if [ "$bt_dev_mac" = "" -o "$channel" = "" ]; then
   	echo "Failed! Exiting..." 
	exit 99 
else 
	printf "OK\n%8s: %-20s\n%8s: %-20s\n\n" \
        "MAC Addr" ${bt_dev_mac} "Channel" $channel
fi

if [ "`ls $btcomdev 2> /dev/null`" = "$btcomdev" ]; then
    echo "releasing $btcomport..."
    sudo rfcomm release $btcomportid 
    sudo hcitool dc $bt_dev_mac
	sleep 1
fi 

echo "Connecting to dev:[$bt_dev_mac]..."
sudo hcitool cc $bt_dev_mac
sudo hcitool con # show connected

echo "Binding remote:[$bt_dev_mac]-ch:[$channel] to local:[$btcomdev]..."
retmsg=`sudo rfcomm bind $btcomportid ${bt_dev_mac} $channel 2>&1 |\
    grep "Address already in use"`
if [ "$retmsg" = "" ]; then
	echo "Done"
else
	echo -e "$retmsg\nRetry..."
	sudo rfcomm release $btcomportid
    sudo hcitool dc $bt_dev_mac
	sleep 1
	sudo rfcomm bind $btcomportid ${bt_dev_mac} $channel
fi

# restart gpsd
echo "stopping gpsd..."
if [ $haspskill -eq 1 ]; then
    pskill gpsd >/dev/null 2>&1
    pskill xgps >/dev/null 2>&1
else
    sudo killall gpsd >/dev/null 2>&1
    sudo killall xgps >/dev/null 2>&1
fi 
echo "starting gpsd..."
sudo gpsd $btcomdev
echo "You can get GPS satellite view with *xgps*!"
#xgps&

# rfcomm0 device identification for Pyserial
#sudo rm /dev/ttyS0 -f && sudo ln -s /dev/rfcomm0 /dev/ttyS0
#ls -l /dev/ttyS0
